﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace VSM
{
    public partial class WSCManagement : System.Web.UI.Page
    {
        private int _rowCount = 0;
        private int _checkRow = 0;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (!IsPostBack)
            {
                ////authorization
                //if (Session[Utils.AppConstants.ManagerUser].ToString() == "")
                //{ //is manager
                //    btn_Submit.Text = "Submit To VSM";
                //}
                //else {//not a manager 
                //    btn_Submit.Text = "Submit To Header";
                //    grdItem.Columns[10].Visible = false;
                //}

                
                DateTime firstDate = DateTime.Today.AddDays(1 - DateTime.Today.Day);
                DateTime firstDateNextMonth = firstDate.AddMonths(1);
                DateTime lastDate = firstDateNextMonth.AddDays(-1);

                txtFromDate.Text = firstDate.ToString("dd/MM/yyyy");
                txtToDate.Text = lastDate.ToString("dd/MM/yyyy");
                createStatusDll();
            }
        }

        private void createStatusDll()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Code");
            dt.Columns.Add("Name");
            dt.Rows.Add("(0, 1, 2, 3, 4, 5, 6)", "All");
            dt.Rows.Add("(0)", "Not Submited");
            dt.Rows.Add("(1)", "Processing");
            dt.Rows.Add("(2, 4, 5, 6)", "Approved");
            dt.Rows.Add("(3)", "Rejected");

            ddlStatus.DataSource = dt;
            ddlStatus.DataTextField = "Name";
            ddlStatus.DataValueField = "Code";
            ddlStatus.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Timer1_Tick(object sender, EventArgs e)
        {
           
        }

       
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdItem_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dt = Session["ItemTable"] as DataTable;
            if (dt != null)
            {
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                this.grdItem.DataSource = Session["ItemTable"];
                this.grdItem.DataBind();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private string GetSortDirection(string column)
        {
            string sortDirection = "ASC";
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdItem_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                if (Session["ChosenItem"] != null)
                {
                    Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                    Label code = (Label)e.Row.FindControl("lblItemCode");
                    try
                    {
                        if (code != null && dicItem[code.Text.Trim()].Length > 0)
                        {
                            CheckBox checkBox = (CheckBox)e.Row.FindControl("chkChild");
                            if (checkBox != null)
                            {
                                checkBox.Checked = true;
                                _checkRow++;
                                if (_checkRow == _rowCount)
                                {
                                    //Check All
                                    GridViewRow headerRow = this.grdItem.HeaderRow;
                                    ((CheckBox)headerRow.FindControl("chkheader")).Checked = true;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //
                    }
                }
            }
        }

       

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void BindBP(DataTable tb)
        {
            Session["ItemTable"] = tb;
            this.grdItem.DataSource = tb;
            this.grdItem.DataBind();
        }

        protected void btn_Filter_Click(object sender, EventArgs e)
        {
            LoadDataFilter();
        }

        private void LoadDataFilter()
        {

            string sql = "select ROW_NUMBER() OVER(ORDER BY A.GeneralID DESC) AS No, * from ( ";
            sql += " select gs.GeneralID, gs.ServiceDate, 'A' WSCType, ";
            sql += " ws.SeqNo, ws.VIN, ws.CustomerName, ws.FailureDate, ws.Model, ws.EngineNumber,   ";
            sql += " ConditionCode, ws.RegistrationNum, gs.Status,   ";
            sql += " case when gs.Status = 0 then 'Not Submited' when gs.Status = 1 then 'Processing' when (gs.Status = 2 or gs.Status = 4 or gs.Status = 5 or gs.Status = 6) then 'Approved'  ";
            sql += " when gs.Status = 3 then 'Rejected' else '' end as StatusName, gs.VSMStatus ";

            sql += " from U_GeneralService gs   ";
            sql += " left join U_WSC ws on gs.GeneralID = ws.GeneralID where gs.JobKind = '004'  ";
            sql += " AND gs.DealerCode = '" + Session[Utils.AppConstants.ID_Dealer] + "' AND WSCType is null ";

            sql += " union all ";

            sql += " select gs.GeneralID, gs.ServiceDate, 'B' WSCType, ";
            sql += " gs.SeqNo, '' as VIN, '' as CustomerName, '' as FailureDate, '' as Model, '' as EngineNumber, ";
            sql += " '' as ConditionCode, '' as RegistrationNum, gs.Status, ";
            sql += " case when gs.Status = 0 then 'Not Submited' when gs.Status = 1 then 'Processing' when (gs.Status = 2 or gs.Status = 4 or gs.Status = 5 or gs.Status = 6) then 'Approved'  ";
            sql += " when gs.Status = 3 then 'Rejected' else '' end as StatusName, gs.VSMStatus ";

            sql += " from U_GeneralService gs ";
            sql += " where gs.JobKind = '004' AND gs.DealerCode = '" + Session[Utils.AppConstants.ID_Dealer] + "' AND WSCType = 'B' ";
            sql += " ) A where 1=1 AND A.Status in " + ddlStatus.SelectedValue;

            //if (ddlStatus.SelectedValue != "-1")
            //{            sql += " case when isnull(gs.VSMStatus, 0) = 1 AND gs.Status = 1 then 'Seen' else '' end as VSMStatusName  ";
            //    sql += " AND A.Status = " + ddlStatus.SelectedValue;
            //}             sql += " case when isnull(gs.VSMStatus, 0) = 1 AND gs.Status = 1 then 'Seen' else '' end as VSMStatusName  ";

            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            grdItem.DataSource = ds.Tables[0];
            grdItem.DataBind();
        }

        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            //Dictionary<string, string> dicItem = new Dictionary<string, string>();
            for (int i = 0; i < this.grdItem.Rows.Count; i++)
            {
                CheckBox checkBox = (CheckBox)this.grdItem.Rows[i].FindControl("chkChild");

                if (checkBox != null)
                {
                    if (checkBox.Checked)
                    {
                        Label gID = (Label)this.grdItem.Rows[i].FindControl("lbGeneralID");

                        Services sv = new Services();
                        sv.ExecuteQuery("DEALER", "UPDATE U_GeneralService SET Status = 1 WHERE GeneralID = " + gID.Text);
                    }
                }
            }
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Update Complete,');", true);
            LoadDataFilter();
        }

    }
}
